package sms

import (
	"encoding/json"
	"fmt"
	"strings"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/cloudwego/hertz/pkg/common/hlog"
)

var dysmsApi *dysmsapi20170525.Client

func Init() error {
	config := &openapi.Config{
		AccessKeyId:     tea.String("LTAI5tMhyZ79R4kxqtTSWRSN"),
		AccessKeySecret: tea.String("rH9xwks7kbwJTYXfmJtEJEed4VvZfA"),
	}
	result, err := dysmsapi20170525.NewClient(config)
	if err != nil {
		return err
	}
	dysmsApi = result
	return nil
}

func SendCaptcha(phone string, captcha string) error {
	if dysmsApi == nil {
		if err := Init(); err != nil {
			return err
		}
	}

	paramJson := fmt.Sprintf("{\"code\":\"%s\"}", captcha)

	hlog.Info(phone)
	hlog.Info(paramJson)

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),
		SignName:      tea.String("陕西向途教育科技"),
		TemplateCode:  tea.String("SMS_486525054"),
		TemplateParam: tea.String(paramJson),
	}

	return Send(sendSmsRequest)
}

func Send(req *dysmsapi20170525.SendSmsRequest) error {
	defer func() error {
		if r := tea.Recover(recover()); r != nil {
			return parseError(r)
		}
		return nil
	}()

	if _, err := dysmsApi.SendSms(req); err != nil {
		hlog.Error(err)
		return parseError(err)
	}
	return nil
}

func parseError(tryErr error) error {
	var err = &tea.SDKError{}
	if _t, ok := tryErr.(*tea.SDKError); ok {
		err = _t
	} else {
		err.Message = tea.String(tryErr.Error())
	}

	// 诊断地址
	var data interface{}
	d := json.NewDecoder(strings.NewReader(tea.StringValue(err.Data)))
	d.Decode(&data)
	if m, ok := data.(map[string]interface{}); ok {
		recommend, _ := m["Recommend"]
		fmt.Println(recommend)
	}
	return err
}
